<?php

namespace App\Console\Commands;

use App\Console\Commands\Common\CommonCommand;
use App\Mail\OrderShipped;
use App\Models\Article\ArticleInfo;
use App\Models\Constant\FileConstant;
use App\Models\User\MemberOrder;
use App\Models\User\SeeLog;
use App\Models\User\User;
use EasyWeChat\Factory;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
use PhpOffice\PhpWord\IOFactory;

class Demo extends CommonCommand {

    public $signature = 'demo {userId?}';



    public function handle() {



        //$this->seeLog();
        $this->test();
    }

    public function test() {
        ArticleInfo::query()
            ->whereDate('publish_at', date('Y-m-d'))
            ->where('publish_at','<=',date('Y-m-d H:i:s'))
            ->orderByDesc('id')
            ->get(['id'])->dump();
    }

    public function seeLog() {

        $days = [
            '2025-11-04',
            '2025-11-03',
            '2025-10-31',
            '2025-10-30',
            '2025-10-29',
            '2025-10-28',
            '2025-10-27',
        ];
        $fileName = Arr::first($days).'至'.Arr::last($days).'阅读下载分析结果.txt';
        $f = fopen(public_path("./$fileName"),'a');
        fwrite($f, "--------------------  阅   ---    读 ----------------------\n");
        foreach ($days as $day) {
            $query = "SELECT
	`user`.id,
	`user`.nick_name,
	see_log.DAY,
	see_log.type,
	count( see_log.article_id ) AS seecount
FROM
	`see_log`
	INNER JOIN `user` ON see_log.user_id = `user`.id
WHERE
	see_log.type = 1
	AND see_log.`day` = '".$day."'
GROUP BY
	see_log.user_id
HAVING seecount>10
ORDER BY seecount desc";
            $records = DB::select($query);
            dump($records);
            fwrite($f, "$day ：\n");
            foreach ($records as $record) {
                fwrite($f, "$record->id | $record->nick_name | 阅读数：$record->seecount \n");
            }
            fwrite($f, "\n");
            fwrite($f, "\n");
        }//endforeach
        fclose($f);
    }

    public function test1() {
        $days = [];
        foreach (range(0, 9) as $num) {
            $days[] = date('Y-m-d',strtotime("-$num day"));
        }
        $records = SeeLog::query()->whereIn('day', $days)->get();
        $userIds = $records->pluck('user_id')->unique()->toArray();
        $users = User::query()->whereIn('id', $userIds)->get();
        $datas = [];
        foreach ($userIds as $userId) {
            $temp = [];
            $logs = $records->where('user_id',$userId);
            foreach ($days as $day) {
                $dayCount = $logs->where('day',$day)->count();
                if($dayCount<10)continue;
                $user = $users->where('id',$userId)->first();
                $temp['userId'] = $user->id;
                $temp['avatar'] = $user->avatar;
                $temp['nick_name'] = $user->nick_name;
                $temp['logs'][] = $day.':'.$dayCount;
                $temp['logs'] = implode('|',$temp['logs']);
            }
            if(count($temp)>0)
                $datas[] = $temp;
        }
        return $datas;
    }

    public function sendEmail() {
        //Mail::to('1043068972@qq.com')->send(new OrderShipped(88300));
    }

    public function syncWxMenu() {
        $config = config('wechat.default');
        $app = Factory::officialAccount($config);

        $buttons = [
            [
                "type" => "view",
                "name" => "搜资料",
                //"url"  => env('APP_URL').'/dist/#/file/login?p=index'
                "url"  => 'https://ctbsc-wap.lyxinxiangyi.cn/'
            ],
            [
                'name'=>'入免费群',
                'sub_button'=>[
                    [
                        "type" => "click",
                        "name" => "入免费群",
                        "key"  => "qun"
                    ],
                    [
                        "type" => "view",
                        "name" => "搜索教程",
                        "url"  => "https://ctbsc-wap.lyxinxiangyi.cn/teach"
                    ],
                    [
                        "type" => "view",
                        "name" => "测试入口",
                        "url"  => "http://tep-wap.lyxinxiangyi.cn/#/login"
                    ],
                ]
            ],
            [
                "type" => "view",
                "name" => "升级会员",
                //"url"  => env('APP_URL').'/dist/#/file/login?p=myInfo'
                "url"  => 'https://ctbsc-wap.lyxinxiangyi.cn/vip'
            ],
        ];

        $res = $app->menu->create($buttons);
        dump($res);
    }

    function truncateHtml($html, $limit) {
        $dom = new DOMDocument();
        @$dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));

        $body = $dom->getElementsByTagName('body')->item(0);
        $result = '';
        $length = 0;

        foreach ($body->childNodes as $node) {
            $nodeHtml = $dom->saveHTML($node);
            $textLength = mb_strlen(strip_tags($nodeHtml));

            if ($length + $textLength > $limit) {
                // 处理部分截断
                $remaining = $limit - $length;
                if ($remaining > 0) {
                    $textContent = $node->textContent;
                    $truncated = mb_substr($textContent, 0, $remaining);
                    $result .= $truncated . '...';
                }
                break;
            }

            $result .= $nodeHtml;
            $length += $textLength;
        }

        return $result;
    }



    public function pushSEO(){
        $urls = array(
            'https://ctb.lyxinxiangyi.cn',
            'https://ctb.lyxinxiangyi.cn/vip',
            'https://ctb.lyxinxiangyi.cn/list/38',
        );
        $api = 'http://data.zz.baidu.com/urls?site=https://ctb.lyxinxiangyi.cn&token=Ox6gAgTbZHDKsj5E';
        $ch = curl_init();
        $options =  array(
            CURLOPT_URL => $api,
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => implode("\n", $urls),
            CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
        );
        curl_setopt_array($ch, $options);
        $result = curl_exec($ch);
        echo $result;
    }

    public function readWordToHtml($source) {

        $phpWord = IOFactory::load($source);
        $html = '';
        foreach ($phpWord->getSections() as $section) {
            foreach ($section->getElements() as $ele1) {
                $paragraphStyle= null;
                if(method_exists($ele1, 'getParagraphStyle')){
                    $paragraphStyle = $ele1->getParagraphStyle();
                }
                if ($paragraphStyle) {
                    $html .= '<p style="text-align:'. $paragraphStyle->getAlignment() .';text-indent:20px;">';
                } else {
                    $html .= '<p>';
                }
                if ($ele1 instanceof \PhpOffice\PhpWord\Element\TextRun) {
                    foreach ($ele1->getElements() as $k=>$ele2) {
                        if ($ele2 instanceof \PhpOffice\PhpWord\Element\Text) {
                            $style = $ele2->getFontStyle();
                            $fontFamily = mb_convert_encoding($style->getName(), 'GBK', 'UTF-8');
                            $fontSize = $style->getSize();
                            $isBold = $style->isBold();
                            $styleString = '';
                            $fontFamily && $styleString .= "font-family:{$fontFamily};";
                            $fontSize && $styleString .= "font-size:{$fontSize}px;";
                            $isBold && $styleString .= "font-weight:bold;";
                            $html .= sprintf('<span style="%s">%s</span>',
                                $styleString,
                                mb_convert_encoding($ele2->getText(), 'GBK', 'UTF-8')
                            );
                        }
                    }
                }elseif ($ele1 instanceof \PhpOffice\PhpWord\Element\Table) {
                    $html.="<table>";
                    foreach ($ele1->getRows() as $row) {
                        $html.="<tr>";
                        foreach ($row->getCells() as $cell) {
                            $html.="<td>";
                            foreach ($cell->getElements() as $c)
                            {
                                $html.=self::getTableTextNode($c);
                            }
                            $html.="</td>";
                        }
                        $html.="</tr>";
                    }
                    $html.="</table>";
                }
                $html .= '</p>';
            }
        }
        return $html;
    }

    public function pay(){
        $order_number = time();
        $user = User::query()->where('id','3')->first();
        $fee = 14.9;
        $config = config('wechat.default');
        $app = Factory::payment($config);
        $result = $app->order->unify([
            'body' => '池塘边素材-会员充值',
            'out_trade_no' => $order_number,
            'total_fee' => $fee,
            'trade_type' => 'NATIVE', // 请对应换成你的支付方式对应的值类型
            'openid' => $user->open_id,
        ]);

    }



    public function formatArticleInfo(){
        ini_set('memory_limit', '-1');
        $records = ArticleInfo::query()->where('id','>=','4494')->whereYear('created_at', 2022)->get();
        foreach ($records as $record) {
            if(!empty($record->img_urls)){
                $record->img_urls = Str::replace('-', '/', $record->img_urls);
            }
            if(!empty($record->img_urls)){
                $record->docx_url = Str::replace('-', '/', $record->docx_url);
            }
            $record->save();
            dump($record->id);
        }
        return 0;
    }

    public function sendHonBao() {
        /*$config = config('wechat.default');
        $payment = Factory::payment($config);
        $redpack = $payment->redpack;

        $redpackData = [
            'mch_billno'   => uniqid().time(),
            'send_name'    => '测试红包',
            're_openid'    => 'oU4Mm6Onl4pbgnvPjkwLHBDdajvY',
            'total_num'    => 1,  //固定为1，可不传
            'total_amount' => 100,  //单位为分，不小于100
            'wishing'      => '祝福语',
            'act_name'     => '测试活动',
            'remark'       => '测试备注',

        ];
        $result = $redpack->sendNormal($redpackData);
        dump($result);*/
    }

    public function syncSummary() {
        $str = '1629,1631,1632,1633,1635,1637,1638,1640,16';
        $ids = explode(',', $str);
        $records = ArticleInfo::whereIn('id',$ids)->get();
        foreach ($records as $record) {

            $path = public_path($record->file_url);
            $body = $this->readWordToHtml($path);

            $record->content = $body;
            $record->save();
            dump($record->id);
        }
    }

    public function createZip(){
        $zipName= uniqid().'.zip';
        $zip = new \ZipArchive();
        $zipFileAbsPath = public_path('fileZip/'.$zipName);
        $zip->open($zipFileAbsPath,\ZipArchive::CREATE);   //打开压缩包

        $records = ArticleInfo::whereIn('id',[7986,7985])->get();

        foreach ($records as $record) {
            if(in_array($record->type, [FileConstant::FILE_TYPE_PPT,FileConstant::FILE_TYPE_PPTX])){
                $absPath = public_path($record->file_url);
                $zip->addFile($absPath,basename($absPath));
                if(!empty($record->docx_url)){
                    $absPath = public_path($record->docx_url);
                    $zip->addFile($absPath,basename($absPath));
                }
            }else{
                $absPath = public_path($record->file_url);
                $zip->addFile($absPath,basename($absPath));
            }
        }
        $zip->close();
        return $zipName;
    }


    public static function getTableNode($node)
    {
        $return = '';
        //处理行
        if ($node instanceof \PhpOffice\PhpWord\Element\Row) {
            foreach ($node->getCells() as $ele)
            {
                $return .= "<tr>".  self::getTableNode($ele)."</tr>";
            }
        }
        //处理列
        else if ($node instanceof \PhpOffice\PhpWord\Element\Cell) {
            foreach ($node->getElements() as $ele)
            {
                $return .= "<td>". self::getTextNode($ele)."</td>";
            }
        }
        return $return;
    }

    public static function getTableTextNode($node)
    {
        $return = '';
        //处理文本
        if ($node instanceof \PhpOffice\PhpWord\Element\Text)
        {
            $txt = $node->getText();
            if(!empty($txt))
                $return .= $txt;
        }
        //处理图片
        else if ($node instanceof \PhpOffice\PhpWord\Element\Image)
        {
            //$return .= self::pic2text($node);
        }
        //处理文本元素
        else if ($node instanceof \PhpOffice\PhpWord\Element\TextRun) {
            foreach ($node->getElements() as $ele) {
                $return .= self::getTextNode($ele);
            }
        }
        return $return;
    }

    public static function getTextNode($node)
    {
        $return = '';
        //处理文本
        if ($node instanceof \PhpOffice\PhpWord\Element\Text)
        {
            $return .=mb_convert_encoding($node->getText(), 'GBK', 'UTF-8');
        }
        //处理图片
        else if ($node instanceof \PhpOffice\PhpWord\Element\Image)
        {
            //$return .= self::pic2text($node);
        }
        //处理文本元素
        else if ($node instanceof \PhpOffice\PhpWord\Element\TextRun) {
            foreach ($node->getElements() as $ele) {
                $return .= self::getTextNode($ele);
            }
        }
        return $return;
    }

}
